/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * newBugView.java
 *
 * Created on 16.01.2010, 22:41:21
 */

package jasebt_app;

import base.Bug;
import base.Project;
import base.Tools;
import base.User;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.TableColumn;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import xmlparser.xmlWriter;
import org.jdesktop.application.Action;
import xmlparser.bugParser;
import xmlparser.deviceParser;
import xmlparser.projectParser;
import xmlparser.stateParser;
import xmlparser.userParser;
/**
 *
 * @author Pavel Belov
 */
public class searchBugView extends javax.swing.JDialog {

    SAXParser parser = null;

    public static User user[];
    public String state[];
    public static String device[];
    public static Project project[];

    private boolean assigneEnabled = false;
    private boolean stateEnabled = false;

    public static String DBPATH = "DB" + File.separator;    

    public Vector bugs = new Vector();

    /** Creates new form newBugView */
    public searchBugView(java.awt.Frame parent) throws SAXException, ParserConfigurationException, IOException {
        super(parent);
        initComponents();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        parser = factory.newSAXParser();
        this.setTitle("Search a bug");

        fillWithUsers();
        fillStates();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bClear = new javax.swing.JButton();
        bCancel = new javax.swing.JButton();
        bSearch = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        taDescription = new javax.swing.JTextField();
        cbAssignee = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cbState = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        taResults = new javax.swing.JTextArea();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();

        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jasebt_app.Jasebt_appApp.class).getContext().getResourceMap(searchBugView.class);
        bClear.setText(resourceMap.getString("bClear.text")); // NOI18N
        bClear.setName("bClear"); // NOI18N
        bClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bClearActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jasebt_app.Jasebt_appApp.class).getContext().getActionMap(searchBugView.class, this);
        bCancel.setAction(actionMap.get("closenewBugForm")); // NOI18N
        bCancel.setText(resourceMap.getString("bCancel.text")); // NOI18N
        bCancel.setName("bCancel"); // NOI18N
        bCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelActionPerformed(evt);
            }
        });

        bSearch.setText(resourceMap.getString("bSearch.text")); // NOI18N
        bSearch.setName("bSearch"); // NOI18N
        bSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSearchActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        taDescription.setText(resourceMap.getString("taDescription.text")); // NOI18N
        taDescription.setName("taDescription"); // NOI18N

        cbAssignee.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbAssignee.setEnabled(false);
        cbAssignee.setName("cbAssignee"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        cbState.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbState.setEnabled(false);
        cbState.setName("cbState"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        taResults.setColumns(20);
        taResults.setEditable(false);
        taResults.setFont(resourceMap.getFont("taResults.font")); // NOI18N
        taResults.setRows(5);
        taResults.setName("taResults"); // NOI18N
        jScrollPane1.setViewportView(taResults);

        jCheckBox1.setSelected(true);
        jCheckBox1.setText(resourceMap.getString("jCheckBox1.text")); // NOI18N
        jCheckBox1.setName("jCheckBox1"); // NOI18N
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jCheckBox2.setSelected(true);
        jCheckBox2.setText(resourceMap.getString("jCheckBox2.text")); // NOI18N
        jCheckBox2.setName("jCheckBox2"); // NOI18N
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(bClear, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bCancel))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jCheckBox2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbAssignee, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jCheckBox1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbState, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(taDescription))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(taDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jCheckBox2)
                    .addComponent(cbAssignee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jCheckBox1)
                    .addComponent(cbState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bClear)
                    .addComponent(bCancel)
                    .addComponent(bSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelActionPerformed
}//GEN-LAST:event_bCancelActionPerformed

    private boolean success(Bug b) {
        if (b.getTitle().startsWith(taDescription.getText()) 
                && ( (!stateEnabled) || (b.getState() == cbState.getSelectedIndex()))
                && ( (!assigneEnabled) || b.getAssignee().equals(cbAssignee.getSelectedItem()))
                ) {
            return true;
        }

        return false;
    }

    // Search for bugs
    private void bSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSearchActionPerformed
        taResults.setText("");
        int bugCount = Tools.getLastBug();
        Bug b = null;

        for (int bugNumber = 0; bugNumber < bugCount; bugNumber++) {
            File bugfile = new File(Tools.getFilePath(bugNumber));
//            System.out.println("Opening bug# " + Integer.toString(bugNumber));
            bugParser bugp = new bugParser();
            if (bugfile.exists()) {
                try {
                    parser.parse(bugfile, bugp);
                    b = bugp.getResult(); 
                    if (success(b) == true) {
                        bugs.add(b.getID());
                        taResults.append("Bug #" + Integer.toString(b.getID()) + ":" + b.getTitle() + "\n");
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(Jasebt_bugView.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Jasebt_bugView.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                b = null;
                System.err.println("File [" + bugfile + "] doesn't exists!");
            }
        }

    }//GEN-LAST:event_bSearchActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    private void bClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bClearActionPerformed
        taResults.setText("");
    }//GEN-LAST:event_bClearActionPerformed

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        assigneEnabled = !assigneEnabled;
        cbAssignee.setEnabled(assigneEnabled);
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        stateEnabled = !stateEnabled;
        cbState.setEnabled(stateEnabled);
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancel;
    private javax.swing.JButton bClear;
    private javax.swing.JButton bSearch;
    private javax.swing.JComboBox cbAssignee;
    private javax.swing.JComboBox cbState;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField taDescription;
    private javax.swing.JTextArea taResults;
    // End of variables declaration//GEN-END:variables

    @Action public void closenewBugForm() {
        dispose();
    }
    // returning users count
    private int OpenUsersDB() throws IOException, SAXException {
        int count = 0;
        userParser up = new userParser();
        File usersFile = new File(DBPATH + "users.xml");

        if (usersFile.exists() == true) {
            parser.parse(usersFile, up);
            count = up.getCount();
            user = new User[count];
            up.fill(user);
            System.out.println("Users count = " + count);
        }

        return count;
    }

    private int OpenStatesDB() throws SAXException, IOException {
        int count = 0;
        stateParser sp = new stateParser();
        File statesFile = new File(DBPATH + "states.xml");

        if (statesFile.exists() == true) {
            parser.parse(statesFile, sp);
            count = sp.getCount();
            state = new String[count];
            sp.fill(state);
        }

        return count;
    }
    private int OpenDevicesDB() throws SAXException, IOException {
        int count = 0;
        deviceParser dp = new deviceParser();
        File deviceFile = new File(DBPATH + "devices.xml");

        if (deviceFile.exists() == true) {
            parser.parse(deviceFile, dp);
            count = dp.getCount();
            device = new String[count];
            dp.fill(device);
        }

        return count;
    }

    private int OpenProjectsDB() throws SAXException, IOException {
        int count = 0;
        projectParser sp = new projectParser();
        File projectsFile = new File(DBPATH + "projects.xml");

        if (projectsFile.exists()) {
            parser.parse(projectsFile, sp);
            count = sp.getCount();
            System.out.println("count projects = " + count);
            project = new Project[count];
            sp.fill(project);
        }

        return count;
    }

    private void fillWithUsers() throws SAXException, IOException {
        int c = OpenUsersDB();

        taDescription.removeAll();
        cbAssignee.removeAllItems();

        for (int i = 0; i < c; i++) {
           cbAssignee.addItem(user[i].getLogin());
        }
    }

    private void fillStates() throws SAXException, IOException {
        int c = OpenStatesDB();
        cbState.removeAllItems();

        for (int i = 0; i < c; i++) {
            cbState.addItem(state[i]);
        }
    }
}
